﻿using MySql.Data.MySqlClient;
using MySqlX.XDevAPI;
using NewChillers.Helpers;
using NewChillers.Models;
using NewChillers.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace NewChillers.ViewModels
{
    public class ChangePasswordViewModel : ObservableObject
    {
        // 通过构造函数接收数据
        private readonly UserModel _currentUser;
        private readonly Window _window;

        // 只读属性
        public string UserAccount => _currentUser.UserAccount;
        public string UserName => _currentUser.UserName;

        // 密码字段
        private string _oldPassword; // 原密码
        private string _newPassword; // 新密码
        private string _confirmPassword; // 确认新密码

        public string OldPassword
        {
            get => _oldPassword;
            set => SetProperty(ref _oldPassword, value);
        }
        public string NewPassword
        {
            get => _newPassword;
            set => SetProperty(ref _newPassword, value);
        }
        public string ConfirmPassword
        {
            get => _confirmPassword;
            set => SetProperty(ref _confirmPassword, value);
        }

        public ICommand ConfirmCommand { get; }
        public ICommand CancelCommand { get; }

        // 构造函数接收传值
        public ChangePasswordViewModel(UserModel currentUser, Window window)
        {
            _currentUser = currentUser; // 接收当前用户数据
            _window = window; // 接收窗口引用用于关闭

            ConfirmCommand = new RelayCommand(ExecuteConfirm);
            CancelCommand = new RelayCommand(ExecuteCancel);
        }

        // 确定按钮执行
        private void ExecuteConfirm(object obj)
        {
            try
            {
                // 输入验证
                if (ValidateInput())
                {
                    // 修改密码
                    if (ChangePassword())
                    {
                        MsgBoxHelper.Success("密码修改成功！");
                        _window.DialogResult = true; // 设置对话框结果
                        return;
                    }
                }
            }
            catch (MySqlException mysqlEx)
            {
                string friendlyMessage = mysqlEx.Number switch
                {
                    1042 => "无法连接数据库，请检查网络连接",
                    1045 => "数据库访问被拒绝",
                    1146 => "数据库表不存在",
                    1205 => "数据库操作超时，请重试", // 死锁
                    1213 => "事务死锁，请重试",      // 死锁
                    0 => "数据库连接失败，请检查网络",
                    _ => $"数据库操作失败，错误代码: {mysqlEx.Number}"
                };
                // 记录数据库异常的日志
                LogHelper.Error(this.GetType(), "[修改密码] | " + "数据库异常", mysqlEx, _currentUser.UserAccount);
                MsgBoxHelper.Error(friendlyMessage);
            }
            catch (Exception ex)
            {
                // 记录修改密码异常的日志
                LogHelper.Error(this.GetType(), "[修改密码]|" + "修改密码异常", ex, _currentUser.UserAccount);
                MsgBoxHelper.Error($"修改密码失败: {ex.Message}");
            }
        }

        // 取消按钮执行
        private void ExecuteCancel(object obj)
        {
            _window.DialogResult = false; // 设置取消结果
        }

        // 输入验证
        private bool ValidateInput()
        {
            if (string.IsNullOrEmpty(OldPassword))
            {
                MsgBoxHelper.Warning("请输入原密码");
                return false;
            }

            if (string.IsNullOrEmpty(NewPassword))
            {
                MsgBoxHelper.Warning("请输入新密码");
                return false;
            }

            if (OldPassword == NewPassword)
            {
                MsgBoxHelper.Warning("新密码不能与原密码相同");
                return false;
            }

            if (NewPassword.Length < 6)
            {
                MsgBoxHelper.Warning("新密码长度不能少于6位");
                return false;
            }

            if (NewPassword != ConfirmPassword)
            {
                MsgBoxHelper.Warning("新密码和确认密码不一致");
                return false;
            }

            return true;
        }

        // 执行密码修改
        private bool ChangePassword()
        {
            bool success = UpdatePasswordInStorage(NewPassword);

            if (success)
            {
                // 记录密码修改成功的日志
                LogHelper.Info(this.GetType(), "[修改密码]|" + "修改密码成功", _currentUser.UserAccount);
                return true;
            }
            else
            {
                // 记录密码修改失败的日志
                LogHelper.Warn(this.GetType(), "[修改密码]|" + "修改密码失败", _currentUser.UserAccount);
                MsgBoxHelper.Warning("原密码不正确，请重新输入");
                OldPassword = string.Empty;
                return false;
            }
        }

        // 验证原密码 修改密码 到数据库
        private bool UpdatePasswordInStorage(string newPassword)
        {
            // UPDATE user_info SET user_password = "1" WHERE user_account = "1"
            string sql = @"UPDATE user_info 
                                SET user_password = @newPassword 
                                WHERE user_account = @account 
                                AND user_password = @oldPassword";

            var parameters = new MySqlParameter[]
            {
                new MySqlParameter("@newPassword", MySqlDbType.VarChar, 20) { Value = newPassword },
                new MySqlParameter("@account", MySqlDbType.VarChar, 20) { Value = _currentUser.UserAccount },
                new MySqlParameter("@oldPassword", MySqlDbType.VarChar, 20) { Value = OldPassword }
            };

            int count = MysqlHelper.ExecuteNonQuery(sql, parameters);
            return count > 0;
        }
    }
}
